public class Test02 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        // 定义两个全局变量
        int ret = -1;
        int count = 0;

        public int kthSmallest(TreeNode root, int k) {
            count = k;
            dfs(root);
            return ret;
        }

        public void dfs(TreeNode root) {
            if (root == null || count == 0) {
                return;
            }
            // 中序遍历
            // 左子树
            dfs(root.left);
            // 根节点
            count--;
            if (count == 0) {
                ret = root.val;
            }
            // 右子树
            dfs(root.right);
        }
    }
}
